export default function ({ $axios, redirect, store, error }, inject) {
  // console.log({ ctx })
  // Create a custom axios instance
  const http = $axios.create({
    headers: {
      common: {
        Accept: 'text/plain, */*',
      },
    },
    // If set to true, http:// in both baseURL and browserBaseURL will be changed into https://.
    https: true,
    // shows a loading bar while making requests integrating Nuxt.js progress bar (see "loading" options in config.nuxt.js).
    progress: true,
    // Adds an interceptor that automatically sets withCredentials axios configuration when issuing a request to baseURL that needs to pass authentication headers to the backend
    credentials: true,
  })

  // Set baseURL to something different
  http.setBaseURL('https://nanchuan.site/api/v1')

  http.onRequest((config) => {
    if (!/^[h/]/.test(config.url)) {
      throw new Error(
        'request path must starts with http[s] or /, but got: ' + config.url
      )
    }
    // console.log('Making request, ', { config })
    if (store.state.token) {
      config.headers.Authorization = store.state.token
      // console.log('Carried token: ', store.state.token)
    }
    // console.log('with headers: ', config.headers)
  })

  // http.onError((err) => {
  //   if (/^[45]/.test(err.response.status)) {
  // return error({
  //   statusCode: 404,
  //   message:
  //     err.detail || err.message || 'Oh Shit! It has gone with the wind!',
  // })
  // }
  // })

  http.onResponse((res) => {
    // console.log({ 'response at axios': res })
    if (res.data && res.data.access_token) {
      http.setToken(res.data.access_token, res.data.token_type)
      store.commit(
        'SET_TOKEN',
        res.data.token_type + ' ' + res.data.access_token
      )
      console.log('TOKEN SET!')
    }
  })

  // Inject to context as $http
  inject('http', http)
}
